<template>
  <div class="app-container">
    <div class="search-container">
      <div class="search-title">
        查询条件
      </div>
      <div class="search-form">
        <div class="form-row">
          <div class="form-column">
            <span class="column-title">姓名</span>
            <el-input v-model="queryParams.personnelName" placeholder="请输入" class="input-w150" clearable @keyup.enter.native="handleQuery" />
          </div>
          <div class="form-column">
            <span class="column-title">审核状态</span>
            <el-select v-model="queryParams.approvalStatusList" multiple placeholder="请选择" class="input-w150" clearable filterable>
              <el-option v-for="dict in approvalStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </div>
          <div class="form-column">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="body-container ">
      <div class="operation-bar">
        <div class="bar-title">
          {{ projectName }} - 成绩列表
          <div class="bar-title__tip">
            <el-select v-model="queryParams.notOrderUnitCodes" multiple placeholder="选择不排序单位" class="input-w150" collapse-tags size="mini" clearable filterable @change="handleQuery">
              <el-option v-for="dict in deptList" :key="dict.id" :label="dict.label" :value="dict.id" />
            </el-select>
          </div>
        </div>
        <div class="bar-btn__wrapper">
          <div class="bar-btn" @click="handleDelAll"><i></i>批量删除成绩</div>
          <div class="bar-btn" @click="handleUploadFile"><i class="el-icon-upload2"></i>导入</div>
          <div class="bar-btn" @click="handleDownLoad"><i class="el-icon-download"></i>导出</div>
        </div>
      </div>

      <el-table v-loading="loading" stripe :data="dataList" sortable="custom" @sort-change="handleTableSortChange" @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55">
        </el-table-column>

        <el-table-column type="index" label="#" align="center" min-width="100"></el-table-column>

        <template v-for="(item, index) of headerList">

          <el-table-column :label="item.label" :sortable="(item.id !== 'personnelName' && item.id!=='remark' && item.id !== 'unitName' && item.id !== 'sex' && item.id !== 'honor' && item.id !== 'scoreOrder' && item.id !== 'unitAverageScore' && item.id !== 'unitScoreOrder')" :prop="item.id" align="center" min-width="150" show-overflow-tooltip :key="`${item.id}$-${index}`">
            <template v-if="item.configList && item.configList.length > 0">
              <el-table-column :label="childItem.label" :min-width="item.id!=='remark'?120:200" align="center" v-for="(childItem, childIndex) of item.configList" :key="childIndex" show-overflow-tooltip>
                <template slot-scope="childScope">
                  <template v-if="!childScope.row.edit">
                    <template v-if="childItem.id === 'cj' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'">
                      {{ childScope.row.subjectScoreMap[`${childItem.key}`].score }}
                    </template>
                    <template v-if="childItem.id === 'df' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'">
                      {{ childScope.row.subjectScoreMap[`${childItem.key}`].grade }}
                    </template>
                    <template v-if="childItem.id === 'df1' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'">
                      {{ childScope.row.subjectScoreMap[`${childItem.key}`].grade1 }}
                    </template>
                    <template v-if="childItem.id === 'df2' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'">
                      {{ childScope.row.subjectScoreMap[`${childItem.key}`].grade2 }}
                    </template>
                    <template v-if="childItem.id === 'pd' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'">
                      {{ childScope.row.subjectScoreMap[`${childItem.key}`].evaluate }}
                    </template>
                    <template v-if="childItem.id === 'df' && childItem.key==='totalScore'">
                      {{ childScope.row.totalScore }}
                    </template>
                    <template v-if="childItem.id === 'pd' && childItem.key==='totalScore'">
                      {{ childScope.row.evaluate }}
                    </template>
                  </template>
                  <template v-else>
                    <el-input type="text" size="mini" v-model.trim="childScope.row.subjectScoreMap[`${childItem.key}`].score" @input="handleNumChange(childScope,childItem,item,childScope.row.subjectScoreMap[`${childItem.key}`],'score')" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'cj' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'"></el-input>
                    <el-input-number type="number" size="mini" v-model.trim="childScope.row.subjectScoreMap[`${childItem.key}`].grade" @input="handleNumChange(childScope,childItem,item,childScope.row.subjectScoreMap[`${childItem.key}`],'grade')" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'df' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'"></el-input-number>
                    <el-input-number type="number" size="mini" v-model.trim="childScope.row.subjectScoreMap[`${childItem.key}`].grade1" @input="handleNumChange(childScope,childItem,item,childScope.row.subjectScoreMap[`${childItem.key}`],'grade1')" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'df1' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'"></el-input-number>
                    <el-input-number type="number" size="mini" v-model.trim="childScope.row.subjectScoreMap[`${childItem.key}`].grade2" @input="handleNumChange(childScope,childItem,item,childScope.row.subjectScoreMap[`${childItem.key}`],'grade2')" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'df2' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'"></el-input-number>
                    <el-input size="mini" v-model.trim="childScope.row.subjectScoreMap[`${childItem.key}`].evaluate" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'pd' && childScope.row.subjectScoreMap[`${childItem.key}`] && childItem.key!=='totalScore'"></el-input>
                    <el-input-number type="number" size="mini" v-model.trim="childScope.row.totalScore" @input="handleNumChange(childScope,childItem,item,childScope.row.totalScore,'total')" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'df'  && childItem.key==='totalScore'"></el-input-number>
                    <el-input size="mini" v-model.trim="childScope.row.evaluate" :min="0" controls-position="right" class="input-w100" v-if="childItem.id === 'pd' && childItem.key==='totalScore'"></el-input>
                    <el-input size="mini" v-model.trim="childScope.row.remark" :min="0" controls-position="right" class="input-w100" v-if="childItem.key === 'remark'"></el-input>
                  </template>
                </template>
              </el-table-column>
            </template>
            <template slot-scope="scope">
              <div v-if="!scope.row.edit">
                <el-link v-if="item.id == 'personnelName'" @click="handleToDetail(scope.row)" :underline="false" type="primary">{{ scope.row[item.id] }}</el-link>
                <template v-else-if="item.id === 'unitName'">
                  <span class="mr4">{{ getDeptName(scope.row.personnelId) }}</span>
                </template>
                <template v-else-if="item.id === 'sex'">
                  <span class="mr4">
                    {{ getGenderStr(scope.row.personnelId)}}
                  </span>
                </template>
                <span v-else class="mr4">{{ scope.row[item.id]
                }}</span>
              </div>
              <div v-else>
                <template v-if="item.id === 'personnelName'">
                  <span class="mr4">{{ scope.row[item.id] }}</span>
                </template>
                <template v-else-if="item.id === 'unitName'">
                  <span class="mr4">{{ getDeptName(scope.row.personnelId) }}</span>
                </template>
                <template v-else-if="item.id === 'sex'">
                  <span class="mr4">
                    {{ getGenderStr(scope.row.personnelId)}}
                  </span>
                </template>
                <template v-else>
                  <el-input v-model.trim="scope.row[item.id]" maxlength="50" v-if="item.id === 'honor'"></el-input>
                  <el-input v-model.trim="scope.row[item.id]" maxlength="50" v-if="item.id === 'remark'"></el-input>
                </template>
              </div>
            </template>
          </el-table-column>
        </template>
        <el-table-column prop="approvalStatus" label="成绩审核状态" align="center" min-width="120">
          <template slot-scope="scope">
            <el-tag size="mini" type="warning" v-if="scope.row.approvalStatus === 1">待审核</el-tag>
            <el-tag size="mini" type="success" v-if="scope.row.approvalStatus === 2">审核通过</el-tag>
            <el-tag size="mini" type="danger" v-if="scope.row.approvalStatus === 3">审核不通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" min-width="240" class-name="small-padding fixed-width">
          <div class="table-option" slot-scope="scope" v-if="scope.row.roleId !== 1">
            <span @click="handleEdit(scope.row)" v-if="!scope.row.edit">编辑成绩</span>
            <span @click="handleSubmit(scope.row)" v-if="scope.row.edit">提交修改申请</span>
            <span @click="handleCancel(scope.row)" v-if="scope.row.edit">取消</span>
            <span @click="handleAddData(scope.row)">添加到人才库</span>
          </div>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>
    <UserDetail :id="personnelId" :visible.sync="userDialog"></UserDetail>

    <!-- 用户导入对话框 -->
    <el-dialog title="导入成绩" :visible.sync="uploadialog" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="fileHeaders" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>

          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownLoad2">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="uploadDisable" :loading="uploadDisable" @click="submitFileForm">确
          定</el-button>
        <el-button @click="uploadialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { queryTrainingSubjectList, findTrainingSubjectResult, delTrainingSubjectPersonnel, addOrUpdateTrainingPersonnelScore, batchDelTrainingPersonnelScore, batchAddTrainingPersonnelScore } from "@/api/subject";
import { addPersonalTalent } from "@/api/talent";
import UserDetail from '@/components/userDetail.vue'
import ExportExcel from '@/utils/excel';
import { getToken } from "@/utils/auth";
import { getDeptName, getDeptNameStr, getGenderStr,getParentId } from "@/utils/ruoyi";

import XLSX from 'xlsx';

export default {
  name: "file",
  dicts: [],
  components: {
    UserDetail
  },
  data () {
    return {
      settingDialog: false,
      uploadDisable: false,
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      upload: {
        isUploading: false,
        updateSupport: 0,
        url: process.env.VUE_APP_BASE_API + '/equipment/import',
      },
      uploadialog: false,
      uploadDisable: false,
      approvalStatusList: [
        { label: '待审核', value: 1 },
        { label: '审核通过', value: 2 },
        { label: '审核不通过', value: 3 }
      ],
      personnelId: '',
      userDialog: false,
      editType: 'add',
      editData: {},
      total: 0,
      editTitle: "",
      editDialog: false,
      dataList: [],
      headerList: [],
      subjectList: [],
      loading: true,
      total: 0,
      multipleSelection: [],
      projectId: '',
      projectName: '',
      queryParams: {
        notOrderUnitCodes: [],
        pageNum: 1,
        pageSize: 10,
        personnelName: undefined,
        orderBySubjectId: undefined,
        orderByType: undefined,
        approvalStatusList: undefined
      },
    };
  },
  computed: {
    deptList () {
      console.log(this.$store.state.user.deptList)
      return this.$store.state.user.deptList
    },
    deptTreeList () {
      return this.$store.state.user.deptTreeList
    },
    userList () {
      return this.$store.state.user.userList
    }
  },
  created () {
    this.projectId = this.$route.query.projectId || ''
    this.projectName = this.$route.query.projectName || ''
    this.getHeader();
  },
  methods: {
    handleSelectionChange (val) {
      console.log(val)
      this.multipleSelection = val;
    },
    async handleDelAll () {
      console.log(this.multipleSelection)
      let list = []
      if (this.multipleSelection.length <= 0) {
        this.$modal.msgWarning('请勾选要删除的数据');
        return
      }
      this.multipleSelection.map(item => {
        list.push({
          personnelId: item.personnelId,
          projectId: this.projectId
        })
      })
      let res = await batchDelTrainingPersonnelScore({
        list: list
      })
      if (res.code === 200) {
        this.$message.success('删除成功！')
        this.getList();
      } else {
        this.$modal.msgWarning(res.msg);
      }
    },
    getDeptName (id) {
      return getDeptNameStr(this.userList, id)
    },
    getGenderStr (id) {
      let str = ''
      let sex = getGenderStr(this.userList, id)
      if (sex === 1) {
        str = '男'
      } else if (sex === 2) {
        str = '女'
      }
      return str
    },
    // 导入文件
    handleUploadFile () {
      this.uploadialog = true
    },
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // // 文件上传成功处理
    async handleFileSuccess (response, file, fileList) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (
        extension !== "xlsx" &&
        extension !== "xlsm" &&
        extension !== "xltx" &&
        extension !== "xltm" &&
        extension !== "xlsb" &&
        extension !== "xls" &&
        extension !== "xlam" &&
        extension !== "csv"
      ) {
        this.$message.warning("只能Excel的文件，请重新上传");
        this.fileList = [];
        return;
      }
      if (size > 10) {
        this.$message.warning("文件大小不得超过10M，请重新上传");
        this.fileList = [];
        return;
      }
      let fileJson = []
      this.file2Xce(file).then(async (tabJson) => {
        if (tabJson && tabJson.length > 0) {
          let tmpList = tabJson[0].sheet || []
          tmpList.map(item => {
            if (item['姓名']) {
              let obj = {
                projectId: this.projectId,
                honor: item['荣誉'] || '',
                remark: item['备注'] || '',
                totalScore: item['总成绩--得分'],
                totalScoreEvaluate: item['总成绩--评定']
              }
              let per = this.dataList.find(dataItem => {
                return dataItem.personnelName === item['姓名']
              })
              console.log(per)
              console.log(per)
              obj['personnelId'] = per.personnelId || ''
              obj['unitCode'] = per.unitCode || ''
              
              let scoreInfoMap = {}
              let keys = Object.keys(item)

              this.headerList.map(headerItem => {
                if (headerItem.flag && item !== '姓名' && item !== '荣誉' && headerItem.id !== 'totalScore') {
                  scoreInfoMap[headerItem.id] = {
                    evaluate: '',
                    grade: 0,
                    grade1: 0,
                    grade2: 0,
                    score: 0
                  }
                }
              })

              for (let i of keys) {
                if (i !== '姓名' && i !== '荣誉') {
                  let strLen = i.split('--')
                  this.headerList.map(headerItem => {
                    if (headerItem.flag) {
                      if (strLen[0] === headerItem.label && strLen[0] !== '总成绩') {
                        let configList = headerItem.configList
                        configList.map(configItem => {
                          if (strLen[1] === configItem.label && configItem.id === 'df') {
                            scoreInfoMap[headerItem.id].grade = item[`${i}`]
                          }
                          if (strLen[1] === configItem.label && configItem.id === 'df1') {
                            scoreInfoMap[headerItem.id].grade1 = item[`${i}`]
                          }
                          if (strLen[1] === configItem.label && configItem.id === 'df2') {
                            scoreInfoMap[headerItem.id].grade2 = item[`${i}`]
                          }
                          if (strLen[1] === configItem.label && configItem.id === 'pd') {
                            scoreInfoMap[headerItem.id].evaluate = item[`${i}`]
                          }
                          if (strLen[1] === configItem.label && configItem.id === 'cj') {
                            scoreInfoMap[headerItem.id].score = item[`${i}`]
                          }
                        })
                      }
                    }
                  })
                }
              }
              console.log(scoreInfoMap)
              obj.scoreInfoMap = scoreInfoMap
              obj.totalScore = ''

              let subjectScoreMap = obj.scoreInfoMap
              let key = Object.keys(obj.scoreInfoMap)
              let total = 0
              for (let i of key) {

                let rowObj = this.headerList.find(rowConfigItem => {
                  return rowConfigItem.id === i
                })

                let weight = (rowObj.weight ? Number(rowObj.weight) : 100)
                let weightVal = weight * 0.01
                let val = Number(subjectScoreMap[i].grade || '0') * (weightVal ? weightVal : 0.1)
                total = total + Number(val.toFixed(2))

                let weight1 = (rowObj.weight1 ? Number(rowObj.weight1) : 100)
                let weightVal1 = weight1 * 0.01
                let val1 = Number(subjectScoreMap[i].grade1 || '0') * (weightVal1 ? weightVal1 : 0.1)
                total = total + Number(val1.toFixed(2))

                let weight2 = (rowObj.weight2 ? Number(rowObj.weight2) : 100)
                let weightVal2 = weight2 * 0.01
                let val2 = Number(subjectScoreMap[i].grade2 || '0') * (weightVal2 ? weightVal2 : 0.1)
                total = total + Number(val2.toFixed(2))

              }
              obj.totalScore = total
              // }
              let parentList=getParentId(this.deptTreeList,obj.unitCode)
              console.log(parentList)
              let parentId=parentList.length>1?parentList[parentList.length-2]:parentList[0]
              console.log(parentId)
              obj.unitCode=parentId.id

              console.log(obj)
              fileJson.push(obj)
            }
          })
          console.log(fileJson)
          let res = await batchAddTrainingPersonnelScore({
            list: fileJson
          })
          if (res.code === 200) {
            this.uploadialog = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.uploadDisable = false;
            this.$message.success('导入成功！')
            this.getList();
          } else {
            console.log('=====', res.msg)
            this.$modal.msgWarning(res.msg);
          }
        }
      })
    },
    // 批量导入客户文件转excel
    file2Xce (file) {
      return new Promise(function (resolve) {
        const reader = new FileReader()
        reader.onload = function (e) {
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: 'binary',
          })
          const result = []
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
            })
          })
          resolve(result)
        }
        reader.readAsBinaryString(file.raw)
      })
    },
    async handleDownLoad2 () {
      console.log(2)
      this.queryParams.projectId = this.$route.query.projectId || ''
      let params = {
        ...this.addStartDateRange(this.queryParams, this.dateRange),
        pageNum: 1,
        pageSize: 9999
      }
      const res = await findTrainingSubjectResult(this.addStartDateRange(this.queryParams, this.dateRange))
      let tmpList1 = res.rows || [];
      let tmpList = tmpList1.reverse()
      let headerList1 = []
      let dataList = []
      let merges = []
      this.headerList.map(item => {
        if (item.flag) {
          let configList = item.configList || []
          let childList = []
          configList.map(configItem => {
            headerList1.push({
              name: item.label + '--' + configItem.label + '',
              prop: `${configItem.id}${configItem.key}`
            })
          })
        } else {
          if (item.label !== '个人排名' && item.label !== '单位均分' && item.label !== '单位排名') {
            headerList1.push({
              name: item.label,
              prop: item.id
            })
          }
        }
      })

      tmpList.map(item => {
        let tmpObj = {}
        tmpObj = {
          personnelName: item.personnelName,
          totalScore: '',
          honor: '',
          remark: '',
          scoreOrder: '',
          unitAverageScore: '',
          unitScoreOrder: '',
          unitName: this.getDeptName(item.personnelId),
          sex: this.getGenderStr(item.personnelId)
        }

        let tmp = null
        if (item.subjectScoreInfoMap) {
          tmp = item.subjectScoreInfoMap
        } else {
          tmp = {}
        }

        tmp['totalScore'] = {
          key: 'totalScore',
          evaluate: '',
          grade: 0,
          grade1: 0,
          grade2: 0,
          score: 0
        }
        if (tmp) {
          let tmpKeysObj = Object.keys(tmp)
          for (let i of tmpKeysObj) {
            tmpObj[`df${i}`] = 0
            tmpObj[`df1${i}`] = 0
            tmpObj[`df2${i}`] = 0
            tmpObj[`cj${i}`] = 0
            tmpObj[`pd${i}`] = ''
          }
        }
        dataList.push(tmpObj)
      })

      let colsW = []
      for (let i = 0; i < headerList1.length; i++) {
        colsW.push({ wpx: 120 })
      }
      const excel = new ExportExcel()
      excel.exportData(dataList, headerList1, '成绩模版', merges, colsW)
    },
    async handleDownLoad () {
      this.queryParams.projectId = this.$route.query.projectId || ''
      let params = {
        ...this.addStartDateRange(this.queryParams, this.dateRange),
        pageNum: 1,
        pageSize: 9999
      }
      const res = await findTrainingSubjectResult(this.addStartDateRange(this.queryParams, this.dateRange))
      let tmpList1 = res.rows || [];
      let tmpList = tmpList1.reverse()
      let headerList1 = []
      let dataList = []
      let merges = []
      this.headerList.map(item => {
        if (item.flag) {
          let configList = item.configList || []
          let childList = []
          configList.map(configItem => {
            childList.push({
              name: configItem.label,
              prop: `${configItem.id}${configItem.key}`
            })
          })
          headerList1.push({
            name: item.label,
            child: childList
          })
        } else {

          headerList1.push({
            name: item.label,
            prop: item.id
          })

        }
      })

      tmpList.map(item => {
        let tmpObj = {}
        tmpObj = {
          personnelName: item.personnelName,
          totalScore: item.totalScore,
          honor: item.honor,
          remark: item.remark,
          scoreOrder: item.scoreOrder,
          unitAverageScore: item.unitAverageScore,
          unitScoreOrder: item.unitScoreOrder,
          unitName: this.getDeptName(item.personnelId),
          sex: this.getGenderStr(item.personnelId)
        }

        let tmp = null
        if (item.subjectScoreInfoMap) {
          tmp = item.subjectScoreInfoMap
        } else {
          tmp = {}
        }

        tmp['totalScore'] = {
          key: 'totalScore',
          evaluate: item.evaluate || '',
          grade: 0,
          grade1: 0,
          grade2: 0,
          score: item.totalScore || 0
        }
        if (tmp) {
          let tmpKeysObj = Object.keys(tmp)
          for (let i of tmpKeysObj) {
            console.log(tmp[i])
            if (i !== 'totalScore') {
              tmpObj[`df${i}`] = tmp[i].grade
              tmpObj[`df1${i}`] = tmp[i].grade1
              tmpObj[`df2${i}`] = tmp[i].grade2
              tmpObj[`cj${i}`] = tmp[i].score
              tmpObj[`pd${i}`] = tmp[i].evaluate
            } else {
              tmpObj[`df${i}`] = tmp[i].score
              tmpObj[`pd${i}`] = tmp[i].evaluate
            }

          }
        }
        dataList.push(tmpObj)
      })

      let colsW = []
      for (let i = 0; i < headerList1.length; i++) {
        colsW.push({ wpx: 120 })
      }
      const excel = new ExportExcel()
      excel.exportData(dataList, headerList1, '成绩列表', merges, colsW)
    },
    handleToDetail (row) {
      this.userDialog = true;
      this.personnelId = String(row.personnelId)
    },
    // // 提交上传文件
    submitFileForm () {
      this.uploadDisable = true;
      this.$refs.upload.submit();
    },
    // 新增到人才库
    async handleAddData (row) {
      let sourceObj = {
        "personnelId": row.personnelId,
      }
      let res = await addPersonalTalent(sourceObj)
      if (res.code === 200) {
        this.$modal.msgSuccess("添加成功");
      } else {
        this.$modal.msgWarning(res.msg);
      }
    },
    // 格式校验
    handleNumChange (childScope, childItem, item, row, key) {
      let rowConfigList = item.configList || []
      console.log(key, row)
      // grade grade1 grade2
      // console.log(childScope.row.subjectScoreMap)
      console.log(this.headerList)

      console.log('--------')

      if ((key === 'grade' || key === 'grade1' || key === 'grade2')) {
        let subjectScoreMap = childScope.row.subjectScoreMap
        let key = Object.keys(subjectScoreMap)
        let total = 0
        for (let i of key) {
          let rowObj = this.headerList.find(rowConfigItem => {
            return rowConfigItem.id === i
          })
          // console.log(rowObj,i)
          //console.log(subjectScoreMap[i])


          console.log(rowObj, i, subjectScoreMap)
          let weight = (rowObj.weight ? Number(rowObj.weight) : 100)
          let weightVal = weight * 0.01
          let val = Number(subjectScoreMap[i].grade || '0') * (weightVal ? weightVal : 0.1)
          total = total + Number(val.toFixed(2))

          console.log('val', Number(subjectScoreMap[i].grade || '0'), (weightVal ? weightVal : 0.1), Number(val.toFixed(2)), 'grade' + subjectScoreMap[i].grade)

          let weight1 = (rowObj.weight1 ? Number(rowObj.weight1) : 100)
          let weightVal1 = weight1 * 0.01
          let val1 = Number(subjectScoreMap[i].grade1 || '0') * (weightVal1 ? weightVal1 : 0.1)
          total = total + Number(val1.toFixed(2))

          console.log('val1', Number(val1.toFixed(2)), 'grade1' + subjectScoreMap[i].grade1)

          let weight2 = (rowObj.weight2 ? Number(rowObj.weight2) : 100)
          let weightVal2 = weight2 * 0.01
          let val2 = Number(subjectScoreMap[i].grade2 || '0') * (weightVal2 ? weightVal2 : 0.1)
          total = total + Number(val2.toFixed(2))

          console.log('val2', Number(val2.toFixed(2)), 'grade2' + subjectScoreMap[i].grade2)

        }
        childScope.row.totalScore = total
      }
    },
    // 排序
    handleTableSortChange (column, prop, order) {
      if (column.prop !== 'totalScore') {
        this.queryParams.orderBySubjectId = column.prop
      } else {
        this.queryParams.orderBySubjectId = ''
        delete this.queryParams.orderBySubjectId
      }
      this.queryParams.orderByType = column.order === 'ascending' ? 1 : 2
      this.handleQuery()
    },
    // 编辑
    handleEdit (row) {
      // row.backData = row
      row.edit = true
    },
    handleCancel (row) {
      row.edit = false
    },
    // 提交申请
    async handleSubmit (row) {
      let sourceObj = {
        "personnelId": row.personnelId,
        "projectId": row.projectId,
        scoreMap: {},
        honor: row.honor,
        remark: row.remark,
        "scoreInfoMap": {}
      }
      let scoreInfoMap = {}
      let subjectMap = Object.keys(row.subjectScoreMap)
      for (let i of subjectMap) {
        if (i !== 'totalScore') {
          let tmp = row.subjectScoreMap[i]
          delete tmp.key
          scoreInfoMap[i] = tmp
        }
        if (i === 'totalScore') {
          sourceObj.totalScore = row.totalScore
          sourceObj.totalScoreEvaluate = row.evaluate
        }
      }

      let parentList=getParentId(this.deptTreeList,row.unitCode)
      let parentId=parentList.length>1?parentList[parentList.length-2]:parentList[0]
      sourceObj.unitCode=parentId.id
      sourceObj.scoreInfoMap = scoreInfoMap
      let res = await addOrUpdateTrainingPersonnelScore(sourceObj)
      if (res.code === 200) {
        this.$modal.msgSuccess("申请成功，请等待审核");
        row.edit = false
        row = row.backData
      } else {
        this.$modal.msgWarning(res.msg);
      }
    },
    // 查询
    async getList () {
      this.loading = true;
      this.queryParams.projectId = this.$route.query.projectId || ''
      const res = await findTrainingSubjectResult(this.addStartDateRange(this.queryParams, this.dateRange))
      this.loading = false;
      if (res.code === 200) {
        let tmpList1 = res.rows || [];
        let tmpList = tmpList1.reverse()
        tmpList.map(item => {
          item.edit = false
          item.backData = JSON.parse(JSON.stringify(item))
          let tmpHeaderList = []
          this.headerList.map(item => {
            if (item.flag) {
              tmpHeaderList.push(item)
            }
          })
          item.subjectScoreMap = {}
          tmpHeaderList.map(headerItem => {
            let tmp = null
            if (item.subjectScoreInfoMap) {
              tmp = item.subjectScoreInfoMap[headerItem.id]
            }
            if (!tmp) {
              if (headerItem.id === 'totalScore') {
                item.subjectScoreMap['totalScore'] = {
                  key: headerItem.id,
                  evaluate: item.evaluate || '',
                  grade: 0,
                  grade1: 0,
                  grade2: 0,
                  score: item.totalScore || 0
                }
              } else {
                item.subjectScoreMap[headerItem.id] = {
                  key: headerItem.id,
                  evaluate: '',
                  grade1: 0,
                  grade2: 0,
                  score: 0
                }
              }
            } else {
              item.subjectScoreMap[headerItem.id] = {
                key: headerItem.id,
                evaluate: tmp.evaluate,
                grade: tmp.grade,
                grade1: tmp.grade1,
                grade2: tmp.grade2,
                score: tmp.score
              }
            }
          })
        })

        this.dataList = tmpList


        console.log(this.headerList)
        console.log(this.dataList)
        this.total = res.total || 0;
      } else {
        this.dataList = [];
        this.total = 0;
      }
    },
    //  // 查询表头
    async getHeader () {
      this.loading = true;
      const res = await queryTrainingSubjectList(this.addStartDateRange({ projectId: this.$route.query.projectId || '', pageNum: 1, pageSize: 99999 }))
      this.loading = false;
      if (res.code === 200) {
        let tmpList = res.rows || []
        this.subjectList = res.rows
        let header = [
          {
            label: '姓名',
            id: 'personnelName'
          },
          {
            label: '单位',
            id: 'unitName'
          },
          {
            label: '性别',
            id: 'sex'
          },
        ]
        tmpList.map(item => {
          if (item.configInfo) {
            let configInfo = JSON.parse(item.configInfo)
            let tmpList = Object.keys(configInfo)
            this.$set(item, 'checkList', tmpList)
            item.configList = []
            console.log('----')
            tmpList.map(tmpItem => {
              console.log(configInfo[tmpItem], tmpItem, item.id)
              if (tmpItem === 'cj') {
                item.configList.unshift({
                  ...configInfo[tmpItem],
                  id: tmpItem,
                  weight: item.weight,
                  weight1: item.weight1,
                  weight2: item.weight2,
                  key: item.id
                })
              } else {
                item.configList.push({
                  ...configInfo[tmpItem],
                  id: tmpItem,
                  weight: item.weight,
                  weight1: item.weight1,
                  weight2: item.weight2,
                  key: item.id
                })
              }
            })
          }
          header.push({
            label: item.subjectName,
            id: `${item.id}`,
            flag: true,
            weight: item.weight,
            weight1: item.weight1,
            weight2: item.weight2,
            configList: item.configList
          })
        })
        header.push({
          label: '总成绩',
          id: 'totalScore',
          flag: true,
          configList: [
            { id: 'df', label: '得分', value: '', key: 'totalScore' },
            { id: 'pd', label: '评定', value: '', key: 'totalScore' },
          ]
        })
        header.push({
          label: '荣誉',
          id: 'honor'
        })
        header.push({
          label: '备注',
          id: 'remark'
        })
        header.push({
          label: '个人排名',
          id: 'scoreOrder'
        })
        header.push({
          label: '单位均分',
          id: 'unitAverageScore'
        })
        header.push({
          label: '单位排名',
          id: 'unitScoreOrder'
        })
        this.headerList = header
        this.getList()
      } else {
        this.dataList = [];
      }
    },
    // 查询
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        pageNum: 1,
        pageSize: 10,
        notOrderUnitCodes: [],
        personnelName: undefined,
        orderBySubjectId: undefined,
        orderByType: undefined,
        approvalStatusList: undefined
      }
      this.handleQuery();
    }
  }
};
</script>